import Hashs from 'jshashes';
import { routerRedux } from 'dva/router';
import { fakeAccountLogin, getMenuAuth, getValid } from '../services/api';
import { setAuthority, setCity, setToken } from '../utils/authority';
import { reloadAuthorized } from '../utils/Authorized';

function getId(json, authArray) {
  if (!json.children) {
    authArray.push(json.id);
    return authArray;
  } else {
    for (let i = 0; i < json.children.length; i++) {
      getId(json.children[i], authArray);
    }
  }
}
export default {
  namespace: 'login',

  state: {
    status: undefined,
    type: 'account',
    message: '',
    verifycode: '',
  },

  effects: {
    *login({ payload }, { call, put }) {
      //console.log('login', payload);
      const { vcode, inputvcode, password, ...params } = payload;
      if (vcode.toLowerCase() !== inputvcode.toLowerCase()) {
        yield put({
          type: 'changeLoginStatus',
          payload: { message: '验证码错误', status: 'error', currentAuthority: 'guest' },
        });
      } else {
        const SHA1 = new Hashs.SHA1().hex(password);
        //console.log('password', SHA1);
        const response = yield call(fakeAccountLogin, {
          ...params,
          password: SHA1,
          verifyCode: inputvcode,
        });
        //console.log('login', response.result);

        // Login successfully

        // for (let i = 0; i < authResponse.amMenuPerm.length; i++) {
        //   authArray = getId(authResponse.amMenuPerm[i], authArray);
        //   //console.log('authArray', authArray);
        // }

        // //console.log('authArray', authArray);

        if (response.result.code === 1000) {
          setToken(response.result.data.token);
          //console.log('login right', response.result.code);
          const authResponse = yield call(getMenuAuth, {
            appId: '3625f952-4a83-4f33-8447-33ecd45e7e14',
          });
          //console.log('auth', authResponse);
          const authArray = ['s1_01'];
          for (let i = 0; i < authResponse.amMenuPerm.length; i++) {
            authArray.push(authResponse.amMenuPerm[i].id);
            if (authResponse.amMenuPerm[i].children.length > 0) {
              for (let j = 0; j < authResponse.amMenuPerm[i].children.length; j++)
                authArray.push(authResponse.amMenuPerm[i].children[j].id);
            }
          }
          yield put({
            type: 'changeLoginStatus',
            payload: { ...response.result, status: true, currentAuthority: authArray },
          });
          reloadAuthorized();
          yield put(routerRedux.push('/'));
        } else {
          yield put({
            type: 'changeLoginStatus',
            payload: {
              ...response.result,
              message: '帐号或密码错误',
              status: 'error',
              currentAuthority: 'guest',
            },
          });
        }
      }
    },
    *logout(_, { put, select }) {
      try {
        // get location pathname
        // const urlParams = new URL(window.location.href);
        // const pathname = yield select(state => state.routing.location.pathname);
        // // add the parameters in the url
        // urlParams.searchParams.set('redirect', pathname);
        // window.history.replaceState(null, 'login', urlParams.href);
      } finally {
        yield put({
          type: 'changeLoginStatus',
          payload: {
            status: false,
            currentAuthority: 'guest',
          },
        });
        reloadAuthorized();
        setCity('初始值');
        setToken('');
        yield put(routerRedux.replace('/user/login'));
      }
    },
    *fetchValid({ payload }, { call, put }) {
      const response = yield call(getValid);
      yield put({
        type: 'changeValid',
        payload: {
          verifycode: response.verifyCode.curVeriCode,
        },
      });
    },
  },

  reducers: {
    changeLoginStatus(state, { payload }) {
      setAuthority(payload.currentAuthority);
      return {
        ...state,
        status: payload.status,
        message: payload.message,
      };
    },
    changeValid(state, { payload }) {
      return {
        ...state,
        verifycode: payload.verifycode,
      };
    },
  },
};
